//
// Created by Administrator on 2022/10/21.
//

//使用数组实现栈结构,称为顺序栈

#include <stdio.h>
#include <malloc.h>

#define MAXSIZE 10
#define ERROR 0
#define OK 1
typedef int ElementType;
typedef int Status;
typedef struct {
    ElementType data[MAXSIZE];
    int top; /* 表示栈顶指针 */
}sqStack;
//初始化一个栈结构
sqStack initSqStack(){
    sqStack* stack= (sqStack*)malloc(sizeof(sqStack));
    (stack)->top=-1;
    return *stack;
}
//压栈操作,放入一个元素到栈中
Status push(sqStack *stack,ElementType e){
    if(stack->top==MAXSIZE-1){
        return ERROR;  // 栈已满
    }

    (*stack).data[++(stack->top)] =e;
    return OK;
}

//出栈操作,删除并返回栈顶元素
Status pop(sqStack *stack,ElementType *e){
    if(stack->top==-1){
        return ERROR; //栈为空
    }
    *e = (*stack).data[(stack->top)--];
    return OK;

}
//显示栈中的所有元素
void showSqStack(sqStack stack){
    int length= stack.top;
    for (int i = 0; i <= length; ++i) {
        printf("%d\n",stack.data[i]);
    }
}
void main(){
    sqStack stack=initSqStack();
    printf("压栈:");
    push(&stack,0);
    push(&stack,1);
    push(&stack,2);
    push(&stack,3);
    push(&stack,4);
    showSqStack(stack);
    printf("开始出栈:\n");
    int tmp;
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    printf("剩余元素为:\n");
    showSqStack(stack);

}

